package com.ruoyi.project.system.device.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PdfCreateUtil {
    //文件路径
    private static String filePath = "D:\\测试文档.pdf";
    //字体文件路径
    private static String fontPath = "C:\\Users\\Administrator\\Downloads\\simsun_itmop.com\\simsun.ttf";
    public static void  createPdf() throws IOException, DocumentException {
        //创建文档对象设置文档大小
        Document document = new Document(PageSize.A4);
        File file = new File(filePath);
        FileOutputStream fos = new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        // 如果直接需要输出到返回流中可以使用一下代码
        // HttpServletResponse res = null; 请求的返回体
        // PdfWriter.getInstance(document,res.getOutputStream());
        //字体
        BaseFont font = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //添加页码
        addFooter(font,12,PageSize.A4,writer);
        document.open();

        //标题字体
        Font titleFont = new Font(font, 12, Font.BOLD);
        //设置每一列宽度
        float[] widths = {50f, 50f, 50f, 50f};
        //创建一个表格对象
        PdfPTable pdfPTable = new PdfPTable(widths);
        PdfPCell pdfPCell = null;
        for (int i = 0; i < 4; i++) {
            pdfPCell = new PdfPCell(new Paragraph("表头1", titleFont));
            //表格内容居中
            pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pdfPTable.addCell(pdfPCell);
        }
        for (int i = 0; i < 20; i++) {
            pdfPCell = new PdfPCell(new Paragraph(i + "", titleFont));
            //表格内容居中
            pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pdfPTable.addCell(pdfPCell);
        }
        document.add(pdfPTable);
        document.close();
    }

    public static void addFooter(BaseFont font,int fontSize,Rectangle pageSize,PdfWriter writer){
        ItextPdfHeaderFooter itextPdfHeaderFooter = new ItextPdfHeaderFooter(font,fontSize,pageSize);
        writer.setPageEvent(itextPdfHeaderFooter);
    }
    public static void main(String[] args) throws IOException, DocumentException {
        createPdf();
    }
}